<?php
    
    $service_key = 'DSbNrMnTBB';  // Key used for dev.

	require_once ("../../config.php");
	require_once ($CFG->dirroot . '/mercurius/lib.php');

    clean_form();

    $sites = array();
    $szResults = 0;
    $tzDiff = date("P");

    // Get lat/lon from point - required field
    //
    $pt = explode(' ', (! empty($_GET['point']) ? $_GET['point'] : ""));
    $lat = 0.0;
    $lon = 0.0;
    if (count($pt) == 2 && is_string_float($pt[0]) && is_string_float($pt[1])) {
        $lon = floatval( $pt[1] );
        $lat = floatval( $pt[0] );
    }

    // Get serviceId - required field; must match our internal value
    //
    $serviceId  = ((isset($_GET['serviceId'])) ? $_GET['serviceId'] : '');

    // Get radius
    //
    $radius = 25;
    if (isset($_GET['radius']) && is_string_float($_GET['radius'])) {
        $radius = floatval( $_GET['radius'] );
    }

    // Get count (max result items to return)
    //
    $count = 20;
    if (isset($_GET['count']) && is_numeric($_GET['count'])) {
        $count = intval( $_GET['count'] );
    }

    // Get sort value, set default if it's something we do not support
    //
    $sort = ((isset($_GET['sort'])) ? strtolower($_GET['sort']) : 'di');
    if (!($sort === 'di' || $sort === 'ti')) {
        $sort = 'di';
    }

    // Get signature value
    // Note: verification of signature not shown...
    //
    $sig = ((isset($_GET['signature'])) ? $_GET['signature'] : '');

	$uri = $_SERVER['QUERY_STRING'];
	$moduri = preg_match ("@^(.+)&signature=.*$@i",$uri,$matches);
	$moduri = $matches[1];
	$nsig = md5($moduri.$service_key);
	
	if($nsig != $sig) {
	    // Header information
	
	    $buf = '<?xml version="1.0" encoding="UTF-8"?>'
	            . "\n<resultSet errorMsg=\"The request does not contain the correct signature."
	            . '<serviceId>' . $SERVICE_ID . '</serviceId>'
	            .  '</resultSet>';
	
	    header("Content-Type: text/xml");
	    echo $buf;
	    exit;
	
	}


    // Valid? Continue...
    //
    if ($lat != 0.0 && $lon != 0.0 && is_numeric($serviceId))
    {
	
		$SERVICE_ID = $serviceId;
		
		$rs = get_record('mercurius_dash_settings','serviceid',$serviceId);
		
		$gpsrecords = get_map_sessions(get_mercurius_user($rs->userid));
		
		$i = 0;
		$szResults = count($gpsrecords);
		foreach($gpsrecords as $index => $log) {
			$logRS = get_record('mercurius_exercise_log','id',$log->session_prkey);
			$sql = "SELECT lat,lon FROM {$CFG->prefix}mercurius_exercise_data WHERE session_prkey = {$log->session_prkey} and Data_type = 2  order by cum_duration asc";
			$logOneRowData = get_record_sql($sql, $expectmultiple=true);
			
			//clean_exercise_log($log);
			
			$sites[$i]["resultId"] = $logRS->id;
			$sites[$i]["title"] = $logRS->title;
			$sites[$i]["description"] = $logRS->notes;
			$sites[$i]['latitude'] = $logOneRowData->lat;
			$sites[$i]['longitude']  = $logOneRowData->lon;
			
		//	$sites[$i]['zip'] = 22203;
		//	$sites[$i]['state'] = "VA";
		//	$sites[$i]['country'] = "USA";
		//	$sites[$i]["phone"] = "301-905-8701";
		//	$sites[$i]['latitude'] = "38.880344";
		//	$sites[$i]['longitude']  = "-77.10826";
			
			$i = $i + 1;
		}

		//stdClass Object ( [id] => 1 [user] => 2 [date] => 2007-12-25 [datetime] => 12:33:13 PM [duration] => 02:54:46 [distance] => 13.00 [distance_unit] => mi [avg_hr] => 155 [max_hr] => 187 [min_hr] => 0 [avg_speed] => 4.46 [max_speed] => 8.40 [speed_unit] => [z1_time] => 00:00:00 [z1_avg_hr] => 0 [z2_time] => 00:57:00 [z2_avg_hr] => 0 [z3_time] => 00:25:00 [z3_avg_hr] => 0 [z4_time] => 00:48:00 [z4_avg_hr] => 0 [z5_time] => 00:41:00 [z5_avg_hr] => 0 [best_pace] => [avg_pace] => [activity] => Mixed [title] => [location] => [public] => 1 [notes] => Ran for about 9 miles and then walked pretty much the rest. The road condition was horrible past 9 miles and I was out of water. ) 
		
        // Extend our radius up to 100 miles to obtain results
        //
		
		/*
		
        for ($miles = 0; $miles < 100; )
        {
            $miles += $radius;

            $radAPI = new MyRadiusApi($lat, $lon, $miles);
            $sql = 'SELECT * FROM my_store '
                . ' WHERE latitude >= ' . $radAPI->minLatitude()
                . ' AND latitude <=  '  . $radAPI->maxLatitude()
                . ' AND longitude >= '  . $radAPI->minLongitude()
                . ' AND longitude <= '  . $radAPI->maxLongitude();

            $sites = $db->performOp( $sql );
            $db->disconnect();

		
		$sites[0]["name"] = "This is a test entry";
		$sites[0]['zip'] = 22203;
		$sites[0]['state'] = "VA";
		$sites[0]['country'] = "USA";
		$sites[0]["phone"] = "301-905-8701";
		$sites[0]['latitude'] = "38.880344";
		$sites[0]['longitude']  = "-77.10826";
		$szResults = count($sites);
		*/
            // Found items: calculate distance, sort, clip, get out
            //
			/*
            if ($sites !== false && ($szResults = count($sites)) > 0)
            {
                $distAPI = new MyDistanceApi;
                $arrSort = array();

                for ($j = 0; $j < $szResults; $j++)
                {
                    $sites[$j]['miles'] = $distAPI->calculate( $lat, $lon,
                                                $sites[$j]['latitude'],
                                                $sites[$j]['longitude'] );
                    if ($sort == 'di') {
                        $arrSort[$j] = $sites[$j]['miles'];
                    } elseif ($sort == 'ti') {
                        $arrSort[$j] = $sites[$j]['name'];
                    }
                }

                array_multisort( $arrSort, SORT_ASC,
                                 (($sort == 'ti') ? SORT_STRING : SORT_NUMERIC),
                                 $sites );
                if ($szResults > $count) {
                    array_splice( $sites, $count );
                    $szResults = $count; 
                }

                break;
            }
			*/
       // } 
    }

    // Header information

    $buf = '<?xml version="1.0" encoding="UTF-8"?>'
            . "\n<resultSet>"
            . '<serviceId>' . $SERVICE_ID . '</serviceId>'
            . '<count>' . $szResults . '</count>'
            . '<sort>' . $sort . '</sort>';

    for ($i = 0; $i < $szResults; $i++)
    {
       // $city = trim($sites[$i]['city'], " ,\t");
      //  $addr = $sites[$i]['address1'];
      //  if (! empty($addr) && ! empty($sites[$i]['address2'])) {
      //      $addr .= ", ";
      //  }
       // $addr .= $sites[$i]['address2'];
      //  $store = strtoupper($sites[$i]["name"]);

        // For the purpose of this example, we insert some random content
        // for some fields...
        //
        $buf .= "\n<result>"
                . '<title>' . $sites[$i]['title'] . '</title>'
                . '<point>'
                    . $sites[$i]['latitude'] . ' ' . $sites[$i]['longitude'] 
                . '</point>'
                . '<description>' . $sites[$i]['description'] . '</description>'
               // . '<timestamp>' . get_random_timestamp() . '</timestamp>'
               // . '<phone>' . $sites[$i]["phone"] . '</phone>' 
               // . '<address>' . clean_entities($addr) . '</address>'
              //  . '<city>' . clean_entities($city) . '</city>'
              //  . '<regionCode>'  . $sites[$i]['state'] . '</regionCode>'
             //   . '<countryCode>' . $sites[$i]['country'] . '</countryCode>'
             //   . '<postalCode>'  . $sites[$i]['zip'] . '</postalCode>'
             //   . '<feature type="rt">' . rand(1, 5) . '/5</feature>'
             //   . '<feature type="pr">$' . rand(1, 15000) . '.00</feature>'
                . '</result>';
    }
    $buf .= '</resultSet>';

    header("Content-Type: text/xml");
    echo $buf;
    exit;


// --------------------------------------------------------------------

function get_random_desc( $store )
{
    return "description goes here";
}

function get_random_timestamp()
{
    // Randomly switches the timezone from the one we are in,
    // to one that falls between the Easten and Pacific zones.
    //
    global $tzDiff;
    return str_replace($tzDiff, ("-0" . rand(4,7) . ":00"), date("c"));
}

function clean_form()
{
    // Clean and trim whitespace from POST/GET vals
    if (count($_GET) > 0) {
        foreach ($_GET as $var => $val) {
            $var = clean_var($var);
            $val = clean_var($val);
            $_GET[$var] = $val;
        }
    }

    if (count($_GET) > 0) {
        foreach ($_GET as $var => $val) {
            $var = clean_var($var);
            $val = clean_var($val);
            $_GET[$var] = $val;

            // most of our ops use POST
            $_GET[$var] = $val;
        }
    }
}

function clean_var($input, $maxlen=0)
{
    $l = ($maxlen == 0 ? strlen($input) : $maxlen);
    if ($l > 80) {
            $l = 80;
    }
    $input = substr(trim(strip_tags($input)), 0, $l);
    $input = ereg_replace("[\'\"\`\~\$]+", '', $input);
    $input = ereg_replace("[\n\r\,\&]+", ' ', $input);
    return ($input);
}

function is_string_float( $str )
{
    return (is_float($str)
            || (((float) $str != round($str)
                || strlen($str) != strlen((int)$str))) && $str != 0);
}

function clean_entities( $str )
{
    return (str_replace( array("&", "'", '"', '<', '>'),
                         array('&#38;', '&#39;', '&#34;', '&#60;', '&#62;'),
                         $str ));
}

?>

